<template>
  <div class="content">
    <div class="breadcrumb">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/callingCard/list' }">文章列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加名片</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="operation">
      <el-button @click="router.go(-1)">返回</el-button>
    </div>
    <el-form class="form-box" ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="名字" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="工作年限" prop="working_years">
        <el-input v-model="formData.working_years" type="number" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="二维码">
        <el-upload class="upload-demo" v-model:file-list="fileList" :action="uploadUrlApi" :headers="{
          // AccessToken: 'xxx'
        }" :on-preview="handlePreview" list-type="picture" :before-upload="beforeUpload" :on-success="handleSuccess" :limit="1">
          <el-button type="primary">上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>

      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { FormRules, FormInstance, ElMessage } from 'element-plus';
import config from '/@/config/index';
import type { UploadProps, UploadUserFile, UploadFile, UploadFiles } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getSession } from '/@/utils';

const baseUrl = config.baseUrl;
const ossUrl = config.ossUrl;
const uploadUrlApi = `${baseUrl}/uploadFile`;

const { proxy }: any = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const formData = reactive({
  name: '', // 姓名
  working_years: '', // 工作年限
  phone: '', // 电话
});
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入', trigger: 'blur' }
  ],
});
const ruleFormRef = ref<FormInstance>();
const textEditorRef = ref(null);

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', formData);
      // const userInfo = getSession('userInfo');
      let res;
      if (!route.query.id) {
        res = await proxy.$http.addCallingCard({
          ...formData,
          // admin_user_id: userInfo.id,
          cover_image: fileList.value[0]?.path || ''
        });
      } else {
        res = await proxy.$http.updateCallingCard({
          ...formData,
          cover_image: fileList.value[0]?.path || ''
        });
      }
      
      if (res.code == config.SUCCESS_CODE) {
        ElMessage({
          message: '操作成功！',
          type: 'success',
        });
        router.push({
          path: '/callingCard/list'
        });
      }
    }
  })
};

// 重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  fileList.value.length = 0;
}

// const fileList = ref<UploadUserFile[]>();
const fileList = ref<any[]>([]);

// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
//   console.log(uploadFile, uploadFiles)
// };

const handlePreview: UploadProps['onPreview'] = (file) => {
  console.log(file)
};

// const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
//   // fileList.value = fileList.value.slice(-3);
//   console.log('change', uploadFile, uploadFiles)
//   if (uploadFile.status != 'fail') {

//   }
// }

// 上传图片前
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgReg = /(jpg|jpeg|png|gif|svg)$/ig;
  if (!imgReg.test(rawFile.type)) {
    ElMessage.error('请上传图片文件!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
}

// NOTE:上传图片成功
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  for (let i = 0; i < uploadFiles.length; i++) {
    if (uploadFiles[i].response) {
      fileList.value.splice(i, 1);
    }
  }
  if (response.code == config.SUCCESS_CODE) {
    fileList.value.push({
      name: uploadFile.name,
      url: ossUrl + response.data.files[0]?.path,
      path: response.data.files[0]?.path,
    });
  } else {
    alert('上传失败:' + response.msg);
    return false;
  }

  console.log(fileList);
};

// 查询详情
const findById = async (id) => {
  const res = await proxy.$http.callingCardById({
    id: id
  });
  if (res.code == config.SUCCESS_CODE) {
    for (let key in res.data) {
      // formData[key] = res.data[key] == null ? '' : res.data[key];
      if (key === 'cover_image' && res.data[key] != '') {
        fileList.value.push({
          url: `${config.ossUrl}${res.data[key]}`,
          name: '二维码',
          path: res.data[key]
        });
      }
    }

    Object.assign(formData, res.data);
    console.log(formData);
  }
};

// 初始化
const init = async () => {
  if (route.query.id) {
    findById(route.query.id);
  }
};

onMounted(() => {
  init();
});

</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  margin-bottom: 100px;
  .operation {
    margin: 10px 0;
  }
  .form-box {
    margin-top: 10px;
    max-width: 1000px;
  }

  .checkbox-box {
    display: flex;
    flex-wrap: wrap;

    .checkbox {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }

  .upload-demo {
    width: 100%;
  }
}
</style>